﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection; 
using System.Text;
using System.Threading.Tasks;

namespace BoriPeter.FitnessJournal8.Models
{
    public static class MergeObjects
    {
        public static T Merge<T>(T obj1, T obj2)
        {
            var props = typeof(T).GetTypeInfo().DeclaredProperties;

            foreach (var prop in props)
            {
                if (prop.CanWrite)
                {
                    Type t = prop.PropertyType;

                    object defaultValueOfProp;
                    try
                    {
                        if (t.IsConstructedGenericType)
                            defaultValueOfProp = null;
                        else
                            defaultValueOfProp = Activator.CreateInstance(t);
                    }
                    catch (Exception)
                    {
                        defaultValueOfProp = null;
                    }

                    var value1 = prop.GetValue(obj1);
                    var value2 = prop.GetValue(obj2);
                    if ((object.Equals(value1, defaultValueOfProp)) &&
                        (!(object.Equals(value2, defaultValueOfProp))))
                    {
                        prop.SetValue(obj1, prop.GetValue(obj2));
                    }
                }
            }

            return obj1;
        }
    }
}
